package com.woniuxy.controller;

import com.woniuxy.pojo.Role;
import com.woniuxy.pojo.User;
import com.woniuxy.service.RoleService;
import com.woniuxy.service.UserService;
import com.woniuxy.util.DataGridView;
import com.woniuxy.util.ResultDto;
import com.woniuxy.vo.RoleVo;
import com.woniuxy.vo.UserVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
public class UserController extends BaseController{

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    //用户分页列表显示
    @GetMapping("/users")
    public DataGridView selectUsersByPage(UserVo userVo) {
        logger.debug("当前页:" + userVo.getPage());
        logger.debug("每页的记录数:" + userVo.getLimit());
        logger.debug("搜索框的信息:" + userVo.getRname());
        return userService.selectUsersByPage(userVo);
    }

    //删除用户
    @DeleteMapping(value = "/users/{id}")
    public ResultDto deleteUser(@PathVariable("id") int id) {
        try {
            this.userService.removeUserById(id);
            return ResultDto.DELETE_USER_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultDto.DELETE_USER_FAILURE;
        }
    }

    //批量删除用户
    @GetMapping(value = "users/deleteBatch")
    public ResultDto deleteBathUser(@RequestParam("ids[]") Integer[] ids) {
        try {
            this.userService.removeBatchUser(ids);
            return ResultDto.DELETE_USER_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultDto.DELETE_USER_FAILURE;
        }
    }

    //增加用户
    @PostMapping(value = "/users.do")
    public ResultDto addUser(User user) {
        Object result = new SimpleHash("md5", user.getLpass(), null, 1024);
        user.setLpass(result.toString());
        User userResult = this.userService.findUserByTel(user.getPhone());
        if (userResult != null) {
            return ResultDto.USER_EXITS;
        } else {
            boolean flag = this.userService.addUser(user);
            if (flag) {
                return ResultDto.USER_ADD_SUCCESS;
            } else {
                return ResultDto.USER_ADD_FAILURE;
            }
        }
    }

    //修改用户
    @PostMapping("/updateEmp.do")
    public ResultDto updateUser(User user) {
        Object result = new SimpleHash("md5", user.getLpass(), null, 1024);
        user.setLpass(result.toString());
        int value = this.userService.updateUser(user);;
        if (value>0) {
            return ResultDto.USER_EDIE_SUCCESS;
        } else {
            return ResultDto.USER_EDIE_FAILURE;
        }
    }

    //用户角色绑定
    @GetMapping("users/initRolesByUsid")
    public DataGridView initRolesByUsid(int usid) {
        logger.debug("用户id:" + usid);
        //查询所有的角色集合
        List<Role> roleList = roleService.findAllRoles();
        //通过用户Id查询该用户所拥有的角色对象集合
        List<Role> roles = this.roleService.selectRolesByUsid(usid);
        List<Role> newsRoleList = new ArrayList<>();
        for (Role role : roleList) {
            boolean LAY_CHECKED = false;
            for (Role roleItem : roles) {
                if (role.getId() == roleItem.getId()) {
                    LAY_CHECKED = true;
                    break;
                }
            }
            RoleVo roleBean = new RoleVo();
            roleBean.setId(role.getId());
            roleBean.setName(role.getName());
            roleBean.setLAY_CHECKED(LAY_CHECKED);
            newsRoleList.add(roleBean);
        }
        return new DataGridView(Long.valueOf(newsRoleList.size()), newsRoleList);
    }

    //分配角色
    @GetMapping(value = "/users/grantRole.do")
    public ResultDto grantRole(int usid, @RequestParam("rids[]") int[] rids) {
        logger.debug("usid:" + usid);
        logger.debug("rids:" + rids);
        try {
            this.userService.grantRole(usid, rids);
            return ResultDto.ROLE_GRANT_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultDto.ROLE_GRANT_FAILURE;
        }
    }

    //修改密码
    @PostMapping("/users/updatePassword")
    public ResultDto changePassword(String rname ,String oldPwd,String newPwd) {
        //从前端获取的旧密码加密
        Object result1 = new SimpleHash("md5", oldPwd, null, 1024);
        String oldPass=result1.toString();
        //通过用户真实姓名查找该用户
        User u= userService.selectUserByRname(rname);
        //判断前端输入的的原密码和数据库查询的用户密码是否一致，如果一致，则修改密码
       if(u.getLpass().toString().equals(oldPass)) {
           //从前端获取的新密码加密
           Object result2 = new SimpleHash("md5", newPwd, null, 1024);
           String newPass = result2.toString();
           //判断原密码与新密码是否相同
           if(!oldPass.equals(newPass)){
               //修改密码
               int value = this.userService.changePassword(rname, newPass);
               if (value > 0) {
                   //获取当前用户的session
                   Subject subject = SecurityUtils.getSubject();
                   Session session=subject.getSession();
                   //移除session
                   session.removeAttribute("USER_SESSION");
                   //退出登录
                   subject.logout();
                   return ResultDto.PWD_MODIFY_SUCCESS;
               } else {
                   return ResultDto.PWD_MODIFY_FAILURE;
               }
           }else{
               return ResultDto.OLD_AND_NEW_PWD_SAME;
           }
       }
        return ResultDto.OLD_PWD_ERROR;
    }

    //个人资料
    @GetMapping("/user/userInfos")
    public User viewUserInfos() {
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        User u = (User) session.getAttribute("USER_SESSION");
        return this.userService.selectUserById(u.getId());
    }
}
